#!/usr/bin/perl
#
# Find the people who have aged out, and freeze them.
#
use strict;
use Counter;
use POSIX qw(strftime O_RDWR);
use DBI;
use Getopt::Long;
use NoteHandler;

use vars qw($freeze $test $users $dbh $sth $days $okfreeze $badfreeze $threemonths $oldonly $badonly);

$okfreeze = 730;
$badfreeze = 365;
$days = 1; # default window size


GetOptions("days=i" => \$days,
	   "oldonly" => \$oldonly,
	   "badonly" => \$badonly,
	   "test" => \$test);


if ($test) {
    warn "TEST mode - not modifying db\n";
    $Counter::User::TESTMODE = 1;
}

$users = Counter::open(O_RDWR);

# The entries are sacrosanct for 3 months after being touched...
$threemonths = strftime "%Y-%m-%d %H:%M:%S", gmtime(time()-(90*3600*24));

if (!$badonly) {
    findandfreeze("all", $okfreeze, $days);
}
if (!$oldonly) {
    findandfreeze("bad", $badfreeze, $days);
    # second sweep to catch those who got updated on the day because of
    # mail sent to their account, and then got marked bad.
    findandfreeze("bad", $badfreeze+95, $days);
}


sub findandfreeze {
    my ($tag, $age, $days) = @_;
    
    my $oldhi = strftime "%Y-%m-%d %H:%M:%S", gmtime(time()-($age*3600*24));
    my $oldlo = strftime "%Y-%m-%d %H:%M:%S", gmtime(time()-(($age+$days)*3600*24));

    warn "$tag: Finding people from $oldlo to $oldhi\n";

    my @cand = $users->select("logintime > ? and logintime < ?
         and f_mtime < ? and state <> 'frozen' and state <> 'blocked'", $oldlo, $oldhi, $threemonths);
    my $n = new NoteHandler;
    print "$tag: Found ", @cand+0, " candidates\n";
    for my $cand (@cand) {
	my @email;
	$n->start($cand->key());
	if ($tag eq "bad") {
	    @email = $cand->emails("main");
	}
	if ($cand->{state} eq "frozen") {
	    $n->done("Already frozen");
	} elsif ($tag eq "bad" && $email[0]->{state} ne "bad") {
	    $n->done("Email not bad");
	} elsif ($$cand{f_mtime} gt $threemonths) {
	    $n->done("Recently touched userrec");
	} else {
	    $n->note("Freezing $$cand{email}");
	    $cand->freeze() if ! $test;
	    $n->done("Frozen");
	}
    }
    $n->report();
}
